import 'package:flutter/material.dart';
//import 'package:amap_map_fluttify/amap_map_fluttify.dart';
//import 'package:amap_base_map/amap_base_map.dart';
// import 'package:map/map.dart';
//import 'package:latlong/latlong.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:amap_location/amap_location.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
class Map extends StatefulWidget {
  Map arguments;
  Map({
    Key key,
    this.arguments,
  }) : super(key: key);

  @override
  _MapState createState() => _MapState(arguments: this.arguments);
}

class _MapState extends State<Map>with AmapSearchDisposeMixin{
  AmapController _controller;
  List<Poi> poiList;
  Location _location;
  String keyword = "";
  String address = "";
  bool isloading = true;
  double longitude;
  double latitude;
  //  final _latController = TextEditingController(text: '39.9824');
  // final _lngController = TextEditingController(text: '116.3053');
  @override
  void initState() {
    super.initState();
    this._getLocation();
    _ser();
    //_seaddress();
  }

  void _getLocation() async {
    //启动一下
    await AMapLocationClient.startup(new AMapLocationOption(
        desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyBest));
    //获取地理位置（直接定位）
    var result = await AMapLocationClient.getLocation(true);
    print('121${result}');
    setState(() {
      // this.longitude = result.longitude; //经度
      // this.latitude = result.latitude; //纬度
      // print(this.longitude);
    });
  }
  List po=[];
  bool lw=false;
  //搜索
  Future <void> _ser ()async{
    final poiList = await AmapSearch.instance.searchKeyword(
               // _keywordController.text,
               //'中国',
               keyword==null?'北京':keyword,
                city: '北京'
                //_cityController.text,
              );
              print(poiList[1]);
              setState(() {
                po=poiList;
                po.length=5;
                lw=true;
               // _getsearch();
              });
  }
  //坐标转地址
  // Future <void>_seaddress()async{
  //   final reGeocodeList = await AmapSearch.instance.searchReGeocode(
  //               LatLng(
  //                 // double.parse(_latController.text),
  //                 // double.parse(_lngController.text),
  //               ),
  //               radius: 200.0,
  //             );
  //             print(reGeocodeList);
  // }
  //搜索选项
  //void _getsearch(){
     List <Widget> _search()=>List.generate(po.length, (index) {
        return ListTile(
         leading: Icon(Icons.location_on),
         title: po.length<0?Text('省市'):Text('${po[index].title}'),
        // title: Text('${po[index].title}'),
         subtitle:po.length<0?Text('详细地址'): Text('${po[index].cityName}${po[index].adName}${po[index].address}'),
         onTap: () async{
          // print(po[index].latLng.latitude);
           _controller?.setCenterCoordinate(
        LatLng(po[index].latLng.latitude, po[index].latLng.longitude),
        animated: true,
      );
         },
         trailing: IconButton(icon: Icon(Icons.call_made), onPressed: (){
            AmapService.instance.navigateDrive(LatLng(po[index].latLng.latitude, po[index].latLng.longitude));
         }),
        );
  });
  //}
 
  Map arguments;
  _MapState({this.arguments});
   AmapController _controller1;
  @override
  Widget build(BuildContext context) {
    //  final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
    // controller.tileSize = 256 / devicePixelRatio;

    return Scaffold(
      resizeToAvoidBottomInset:false,
        appBar: AppBar(
            title: Text('请选择位置信息'),
            backgroundColor: Color(0xFFFFCA28),
            ),
        body: Column(
          children: <Widget>[
            Theme(
              data: new ThemeData(
                  primaryColor: Color(0xFFFFCA28),
                  hintColor: Color(0xFFFFCA28)),
              child: Container(
                color: Color(0xFFFFCA28),
                padding: EdgeInsets.all(5),
                child: Container(
                  height: 36,
                  margin: EdgeInsets.only(left: 5, right: 5, bottom: 5),
                  child: TextField(
                    style: TextStyle(fontSize: 16, letterSpacing: 1.0),
                    controller:
                        TextEditingController.fromValue(TextEditingValue(
                      // 设置内容
                      text: keyword,
                      selection: TextSelection.fromPosition(TextPosition(
                          affinity: TextAffinity.downstream,
                          offset: keyword?.length ?? 0)),
                      // 保持光标在最后
                    )),
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(40)),
                      ),
                      hintText: '输入关键字',
                      hintStyle:
                          TextStyle(color: Color(0xFFBEBEBE), fontSize: 14),
                      contentPadding: const EdgeInsets.symmetric(
                          vertical: 8, horizontal: 1),
                      prefixIcon: Icon(
                        Icons.search,
                        color: Colors.grey,
                        size: 20,
                      ),
                      suffixIcon: IconButton(
                        icon: Icon(
                          Icons.clear,
                          color: Colors.grey,
                          size: 20,
                        ),
                        onPressed: () {
                          keyword = "";
                          setState(() {

                          });
                        },
                      ),
                      fillColor: Colors.white,
                      filled: true,
                    ),

                    inputFormatters: [],
                    //内容改变的回调
                    onChanged: (text) {
                      print('change $text');
                      keyword = text;
                    },
                    //内容提交(按回车)的回调
                    onSubmitted: (text) {
                      print('submit $text');
                      // 触发关闭弹出来的键盘。
                      keyword = text;
                      _ser();
                      setState(() {
                        isloading = true;
                        FocusScope.of(context).requestFocus(FocusNode());
                      });

                      // searchAroundAddress(text.toString());
                    },
                    //按回车时调用
                    onEditingComplete: () {
                      print('onEditingComplete');
                    },
                  ),
                ),
              ),
            ),
            Container(
              height: 300,
              child: AmapView(
                mapType: MapType.Standard,
                showZoomControl: true,
                maskDelay: Duration(milliseconds: 500),
                markers: <MarkerOption>[],
                showScaleControl: true,
                 zoomLevel: 12,
                // centerCoordinate: LatLng(23.16, 113.23),
               centerCoordinate: LatLng(this.latitude, this.longitude),
                onMapCreated: (controller) async {
                  _controller = controller;
                  _controller1=controller;
                  await _controller?.showLocateControl(true);
                 await _controller?.showCompass(true);
                  await _controller.showMyLocation(MyLocationOption(
                    show: true,
                    myLocationType: MyLocationType.Locate,
                   //interval: Duration.zero,
                    strokeColor: Colors.pink,
                    // interval: Duration(seconds: 10),
                  ));
                  print('初始化');
                  await _controller.requireAlwaysAuth();
                  await _controller.setZoomLevel(17.0);
                  // final latLng = await _controller?.getLocation( timeout: Duration(seconds: 2),interval:Duration(milliseconds: 500));
                  // final lat = await _controller?.getLocation();
                   //print('定位${latLng.latitude}${latLng.longitude}');
                },
                onMapMoveEnd: (MapMove move) async {
                  print('位置${move.latLng.latitude.toString()}');
                  //print('位置1${move.}');
                  var c=move.latLng.latitude.toString();
                  var c1=move.latLng.longitude.toString();
                  setState(() {
                    //_seaddress(c,c1);
                   // this.latitude=23.16;
                   // this.longitude=113.23;
                    //this.latitude=move.latLng.latitude;
                   // this.longitude=move.latLng.longitude;
                  });
                  if (await requestPermission()) {
                  await AmapLocation.instance.stopLocation();
                  setState(() => _location = null);
                }
                   // _loadData(move.latLng);
                  },
                onMapClicked: (val) async {
                  _controller.showLocateControl(true);
                  _controller.setMapClickedListener((latLng)async{
                    print(latLng);
                  }  );
                  // setState(() {
                  //   this.latitude = val.latitude;
                  //   this.longitude = val.longitude;
                  // });
                  print('我');
                  // final center = await _controller?.getCenterCoordinate();
                  // setState(() {
                  //   this.latitude = center.latitude;
                  //   this.longitude = center.longitude;
                  // });
                  // print(center);
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: ListView(
              children: //<Widget>[Text('你好')]
               _search()
            //  <Widget>[
                
            //    // Text('你好')
            //     ListTile(
            //       title: Center(child: Text('监听位置改变')),
            //       onTap: () async {
            //         _ser();
            //         // await _controller
            //         //     ?.setMyLocationChangeListener((location) async {
            //         //   final coord = await location.coord;
            //         //   print(
            //         //     '当前位置: 经度: ${coord.latitude}, 纬度: ${coord.longitude}, 方向: ${await location.bearing}',
            //         //   );
            //         // });
            //       if (await requestPermission()) {
            //       final location = await AmapLocation.instance.fetchLocation();
            //       print(location.latLng.longitude);
            //     //   _controller?.setCenterCoordinate(
            //     //           LatLng(23.16, 113.23),
            //     //           animated: false,
            //     //         );
            //     //  setState(() {
            //     //     this.latitude=23.16;
            //     //     this.longitude=113.23;
            //     //  });
            //        //print(location);
            //        setState(() {
            //          this.latitude=location.latLng.latitude;
            //          this.longitude=location.latLng.longitude;
            //        });
            //     setState(() => _location = location);
            //     }
            //       },
            //     ),
            //   ],
            ),
            )
                 
               
          ],
        ));
  }
}
Future<bool> requestPermission() async {
  final permissions =
      await PermissionHandler().requestPermissions([PermissionGroup.location]);

  if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
    return true;
  } else {
    print('需要定位权限!');
    return false;
  }
}